﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SuperSocket.ClientEngine;
using System.Net;
using IUploading;
using System.IO;

namespace UploadTestClient
{
    public partial class Form1 : Form
    {
        private bool Connected = false;

        private List<InterfaceConfig> ListInterfaces = new List<InterfaceConfig>();

        public Form1()
        {
            InitializeComponent();
        }

        private void LoadInterface()
        {
            //配置文件路径
            string file = Application.StartupPath + "\\Config\\" + "Interfaces.xml";
            InterfaceConfigReader<InterfaceConfig> reader = new InterfaceConfigReader<InterfaceConfig>(file);
            //读配置
            if (!reader.Load())
            {
                MessageBox.Show("设备配置信息加载失败!\n" + reader.ErrorMessage);
            }
            ListInterfaces = reader.ListInterfaces;
        }

        private void InitComboxBoxs()
        {
            comboBox1.Items.Clear();
            foreach (InterfaceConfig config in ListInterfaces)
            {
                comboBox1.Items.Add(config.InterfaceName);
            }
            comboBox1.SelectedIndex = 0;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadInterface();
            InitComboxBoxs();
        }      

        private void buttonExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            ConnectToServer();
        }

        private void buttonDisconnect_Click(object sender, EventArgs e)
        {
            if (Connected)
            {
                ssClient.Close();
                Connected = false;
            }
        }

        public EasyClient<TransferResponsePackageInfo> ssClient = null;

        public void ConnectToServer()
        {
            ssClient = new EasyClient<TransferResponsePackageInfo>();
            ssClient.Initialize(new TransferResponseReceiveFilter());
            ssClient.Connected += OnClientConnected;
            ssClient.NewPackageReceived += OnPackageReceived;
            ssClient.Error += OnClientError;
            ssClient.Closed += OnClientClosed;
            ssClient.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6669));
        }

        private void OnPackageReceived(object sender, PackageEventArgs<TransferResponsePackageInfo> e)
        {
            if (this.InvokeRequired)
            {
                EventHandler<PackageEventArgs<TransferResponsePackageInfo>> handler = new EventHandler<PackageEventArgs<TransferResponsePackageInfo>>(OnPackageReceived);
                this.BeginInvoke(handler, new object[] { sender, e });
                return;
            }
            TransferResponsePackageInfo packageInfo = e.Package;
            TransferResponsePackge pack = packageInfo.Packge;
            richTextBoxReceived.AppendText(pack.OutParams + Environment.NewLine);

        }

        private void OnClientConnected(object sender, EventArgs e)
        {
            if (this.InvokeRequired)
            {
                EventHandler handler = new EventHandler(OnClientConnected);
                this.BeginInvoke(handler, new object[] { sender, e });
                return;
            }
            Connected = true;
            richTextBoxReceived.AppendText("已连接到服务器..." + Environment.NewLine);
        }

        private void OnClientClosed(object sender, EventArgs e)
        {
            if (this.InvokeRequired)
            {
                EventHandler handler = new EventHandler(OnClientConnected);
                this.BeginInvoke(handler, new object[] { sender, e });
                return;
            }
            richTextBoxReceived.AppendText("连接已断开..." + Environment.NewLine);           
        }

        private void OnClientError<ErrorEventArgs>(object sender, ErrorEventArgs e)
        {
            if (this.InvokeRequired)
            {
                EventHandler handler = new EventHandler(OnClientError);
                this.BeginInvoke(handler, new object[] { sender, e });
                return;
            }
            richTextBoxReceived.AppendText("客户端错误：" + e.ToString() + Environment.NewLine);
        }

        private void buttonLogin_Click(object sender, EventArgs e)
        {
            TransferDataPackge pack = new TransferDataPackge();
            pack.InterfaceName = comboBox1.SelectedItem.ToString();
            pack.Action = TransferAction.Login;
            pack.Add("Path", @"D:\Newest");
            pack.Add("Key", "Login");
            SendDataToServer(pack);
        }

        private void buttonLogout_Click(object sender, EventArgs e)
        {
            TransferDataPackge pack = new TransferDataPackge();
            pack.InterfaceName = comboBox1.SelectedItem.ToString();
            pack.Action = TransferAction.Logout;
            pack.Add("Path", @"D:\Newest");
            pack.Add("key", "Logout");
            SendDataToServer(pack);
        }

        private void buttonTest_Click(object sender, EventArgs e)
        {
            TransferDataPackge pack = new TransferDataPackge();
            pack.InterfaceName = comboBox1.SelectedItem.ToString();
            pack.Action = TransferAction.Test;
            pack.Add("key", "test");
            SendDataToServer(pack);
        }

        private void buttonPost_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxOrigFilePath.Text) 
                || string.IsNullOrEmpty(textBoxDestFilePath.Text))
            {
                MessageBox.Show("没有选择文件");
                return;
            }

            string origFileName = textBoxOrigFilePath.Text;
            if (!File.Exists(origFileName))
            {
                MessageBox.Show("指定的文件不存在");
                return;
            }

            string destFileName = textBoxDestFilePath.Text;
            if (!File.Exists(destFileName))
            {
                MessageBox.Show("指定的文件不存在");
                return;
            }

            TransferDataPackge pack = new TransferDataPackge();
            pack.InterfaceName = comboBox1.SelectedItem.ToString();
            pack.Action = TransferAction.Post;
            pack.Add("PhotoName", "testfileName");
            pack.Add("OrigPhotoPath", origFileName);
            pack.Add("DestPhotoPath", destFileName);
            SendDataToServer(pack);
        }

        private void SendDataToServer(TransferDataPackge sendPackge)
        {
            byte[] dataBody = MsgPackHandler.ConvertToBytes<TransferDataPackge>(sendPackge);

            // 协议命令占16位, 如果占的位数长过协议，那么协议解析会出错的
            var commandData = Encoding.UTF8.GetBytes(sendPackge.Action);

            // 长度int类型占4位，根据协议这里也只能4位，否则会出错
            var dataLen = BitConverter.GetBytes(dataBody.Length);

            // 命令加内容长度为20
            var sendData = new byte[20 + dataBody.Length];
            // +-------+---+-------------------------------+
            // |request |  l |                               |
            // | name   | e |    request body       |
            // |  (16 )    | n |                               |
            // |             |(4)|                               |
            // +-------+---+-------------------------------+
            Array.ConstrainedCopy(commandData, 0, sendData, 0, commandData.Length);
            Array.ConstrainedCopy(dataLen, 0, sendData, 16, 4);
            Array.ConstrainedCopy(dataBody, 0, sendData, 20, dataBody.Length);
            ssClient.Send(sendData);
        }

        private void buttonOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog form = new OpenFileDialog();
            form.InitialDirectory = "E:\\Photos";
            form.Filter = "照片(*.png,*.jpg,*.bmp)|*.png;*.jpg;*.bmp|所有文件|*.*";
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBoxOrigFilePath.Text = form.FileName;
            }
        }

        private void buttonOpenDestFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog form = new OpenFileDialog();
            form.InitialDirectory = "E:\\Photos";
            form.Filter = "照片(*.png,*.jpg,*.bmp)|*.png;*.jpg;*.bmp|所有文件|*.*";
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBoxDestFilePath.Text = form.FileName;
            }
        }

    }
}
